﻿using System;
using System.Collections.Generic;
using UnityEngine;

namespace UFrame.ECS
{
    /// <summary>
    /// 管理和调试用
    /// 支持UComponent组件的对象池
    /// UWorld 支持模板方式创建UEntity
    /// </summary>
    public class UWorld
    {
        public List<UEntity> entityList = new List<UEntity>();
        public Dictionary<int, List<UComponent>> comPool = new Dictionary<int, List<UComponent>>();
        public List<TemplateEntity> templateEntity = new List<TemplateEntity>();

        public UEntity CreateEntity(int template = -1)
        {
            //搜索有没有Entity模板
            UEntity u = new UEntity();
            entityList.Add(u);

            if (template != -1)
            {
                TemplateEntity te = null;
                for (int i = 0; i < templateEntity.Count; i++)
                {
                    if (templateEntity[i].id == template)
                    {
                        te = templateEntity[i];
                        break;
                    }
                }

                if (te != null)
                {
                    for (int i = 0; i < te.uComponent.Count; i++)
                    {
                        u.AddComponent(Activator.CreateInstance(te.uComponent[i]) as UComponent);
                    }
                    for (int i = 0; i < te.system.Count; i++)
                    {
                        u.AddUSystem(Activator.CreateInstance(te.system[i]) as USystem);
                    }
                }
            }

            return u;
        }

        public void AddUCom(UComponent u)
        {
            int has = u.GetType().GetHashCode();
            if (comPool.ContainsKey(has))
            {
                comPool[has].Add(u);
            }
            else
            {
                List<UComponent> uList = new List<UComponent>();
                uList.Add(u);
                comPool.Add(has, uList);
            }
        }

        public T GetUCom<T>() where T : UComponent, new()
        {
            int code = typeof(T).GetHashCode();
            if (comPool.ContainsKey(code))
            {
                var list = comPool[code];
                var t = list[list.Count - 1];
                comPool[code].RemoveAt(list.Count - 1);
                return (T) t;
            }

            return new T();
        }
    }

    public class TemplateEntity
    {
        public int id;
        public List<Type> system;
        public List<Type> uComponent;
    }
    
}